package com.jbit.hxy.controller;

import cn.hutool.core.io.file.FileNameUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.jbit.hxy.common.Result;
import com.jbit.hxy.config.OssConfig;
import com.jbit.hxy.model.po.WxUser;
import com.jbit.hxy.service.user.WxUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.MultipartConfigElement;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/oss")
@RequiredArgsConstructor
@Tag(name = "文件上传接口")
public class upLoadController {
    private static final List<String> IMAGE_TYPE = Arrays.asList("png", "jpg", "jpeg");

    /*
        #上传文件时，默认单个上传文件大小是1MB，max-file-size设置单个上传文件大小
        spring.servlet.multipart.max-file-size=50MB
        #默认总文件大小是10MB，max-request-size设置总上传文件大小
        spring.servlet.multipart.max-request-size=500MB
        byte[]getBytes() 获取文件数据
        String getContentType() 获取文件MIME类型
        InputStream getInputStream() 获取表单中文件组件的名字
        String getName() 获取表单中文件组件的名字
        String getOriginalFilename() 获取上传文件的原名
        long getSize() 获取文件的字节大小
        boolean isEmpty() 是否有选择上传文件
        void transferTo() 将上传文件保存到一个目标文件中


         // 设置上传后的文件名称（拼接）
        String newFileName = username + UUID.randomUUID() + "_" + originalFilename;
     */

    @Resource
    private OSS ossClient;



    @Resource
    private MultipartConfigElement multipartConfigElement;

    @Resource
    private OssConfig ossConfig;


    private String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }
    @Operation(summary = "上传用户头像")
    @PostMapping(value = "/uploadAvater", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result uploadAvater(@RequestParam("file") MultipartFile file) {
        String bucketName = ossConfig.getBucketName();
        String endPoint = ossConfig.getEndPoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        // png、jpg、jpeg   10MB
        if (file == null || file.getSize() == 0) {
            return Result.fail("上传头像不能为空");
        }
        String fileName = file.getOriginalFilename();
        String fileSuffix = fileName.substring(fileName.lastIndexOf(".")); // .jpg
        String fileExt = FileNameUtil.extName(fileName); // jpg
        Long fileSize = file.getSize();
        if (!IMAGE_TYPE.contains(fileExt)) {
            return Result.fail("上传头像格式错误，仅支持(.jpg,.jpeg,.png)格式");
        }
        if (fileSize > multipartConfigElement.getMaxFileSize()) {
            return Result.fail("上传头像大小不能超过10MB");
        }
        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        String uploadFileName = fileName;

        try {
            PutObjectResult result = ossClient.putObject(bucketName, uploadFileName, file.getInputStream());
            //拼装返回路径
            if (result != null) {
//                String createdUser = String.valueOf(StpUtil.getExtra("username"));
//                Integer userId = StpUtil.getLoginIdAsInt();
                fileName = fileName.substring(0, fileName.lastIndexOf("."));
//                String imageUrl = "https://"+bucketName+"."+endPoint+"/"+uploadFileName;
                HashMap<String, String> objectObjectHashMap = new HashMap<>();
//                Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
                String url = "https://" + bucketName + ".oss-cn-hangzhou.aliyuncs.com/" + uploadFileName;
//                URL imageUrl = ossClient.generatePresignedUrl(bucketName, uploadFileName, expiration);
                objectObjectHashMap.put("url", url);
                objectObjectHashMap.put("path", uploadFileName);

                System.out.println(url);
//                userMapper.updateAvater(id,imageUrl.toString());
//                if (!(userMapper.selectCount(new QueryWrapper<User>().eq("title", fileName)) > 0)) {
//                    documentMapper.saveDoc(fileName, fileExt, imageUrl.toString(), uploadFileName, createdUser, userId, 0);
//                }
//                } else {
//                    return SaResult.error("不能重复上传！");
//                }
                return Result.success(objectObjectHashMap);
            }
        } catch (IOException e) {
            return Result.fail("头像上传失败");
        } finally {
            //OSS关闭服务，不然会造成OOM
            ossClient.shutdown();
        }
        return Result.fail("头像上传失败");

    }
}
